<template>
	<view class="product-container">
		<u-navbar :border-bottom="false" :title="title" :background="{'background':'#fff'}" :title-size="36" :title-bold="true" :title-color="textColor">
			<view class="u-p-r-20" style="color:#ff551a;" slot="right" @click="delModel = true" v-if="title == '编辑商品'">
				删除
			</view>
		</u-navbar>
		<view class="u-p-35">
			<u-form :model="fromData" ref="uForm" :label-position="'top'"	:label-style="labelStyle">
					<u-form-item label="商品名称" prop="name">
						<u-input v-model="fromData.name" placeholder="请输入商品名称"/>
					</u-form-item>
					<u-form-item label="商品简称" prop="abbreviation">
						<u-input v-model="fromData.abbreviation" placeholder="请输入商品简称"/>
					</u-form-item>
					<u-form-item label="规格" prop="specification">
						<u-input v-model="fromData.specification"  placeholder="请输入商品规格"/>
					</u-form-item>
					<u-form-item label="终端价格" prop="price">
						<u-input v-model="fromData.price" type="number"  placeholder="请输入商品终端价格"/>
					</u-form-item>
					<u-form-item label="商品单位" prop="unit">
						<u-input v-model="fromData.unit"  placeholder="请输入商品单位"/>
					</u-form-item>
					<u-form-item label="商品编码" >
						<u-input v-model="fromData.barcode" type="number" placeholder="请输入商品编码(12-13位数字)"/>
					</u-form-item>
					<u-form-item label="商品图片" prop="itemFocus">
						<UploadImage :fileList="itemImageList" @onSuccess="uploadItemChange" @onRemove="uploadItemChange" :maxCount="4"></UploadImage>
					</u-form-item>
					<u-form-item label="商品缩略图" prop="resourceId">
						<UploadImage :fileList="resourceList" @onSuccess="uploadResChange" @onRemove="uploadResRemove" :maxCount="1"></UploadImage>
					</u-form-item>
					<u-form-item label="商品分类图" prop="pureResourceId">
						<UploadImage :fileList="pureResourceList" @onSuccess="uploadPureChange" @onRemove="uploadPureRemove" :maxCount="1"></UploadImage>
					</u-form-item>
					<u-form-item label="视频封面图" >
						<UploadImage :fileList="videoImageList" @onSuccess="uploadVideoChange" @onRemove="uploadVideoRemove" :maxCount="1"></UploadImage>
					</u-form-item>
					<u-form-item label="添加视频" >
						<view class="u-flex u-row-between" style="width: 100%;">
							<u-input v-model="fromData.videoUrl" :disabled="fromData.videoResourceId"  placeholder="输入视频网络地址或点击上传" style="flex:1;overflow: hidden;"/>
							<u-upload :action="baseUrl + 'api/Resource/UploadToOss'"
								:header="uploadHeader" 
								 :max-count="1"
								 :source-type="['album']"
								 @on-success="onVideoSuccess"
								 @on-remove="onVideoRemove"
								 :custom-btn="true"
								 :show-progress="false"
								 :show-upload-list="false"
								 :isSlot="true"
								 style="width: 120rpx;margin-left: 20rpx;"
								 v-if="!fromData.videoResourceId"
								 >
									<view class="" style="color: #ff551a;" slot="addBtn">
										本地上传
									</view>
								 </u-upload>
								 <view class="" v-else style="width: 70rpx;margin-left: 20rpx;color: #ff551a;" @click="onVideoRemove">
								 	删除
								 </view>
						</view>
					</u-form-item>
					<u-form-item label="平台分类"  prop="categoryId">
						<view class="u-flex u-row-between" style="width: 100%;" @tap="$mRouter.push({ route: '/pages/owners/productMange/plateClass?isChoose=true&name='+fromData.platformCategoryName+'&id='+fromData.platformCategoryId })">
							<view class="" style="flex:1;">
								<text :style="{'color':fromData.platformCategoryId?'#333':'rgb(192, 196, 204)'}">{{fromData.platformCategoryName||'请选择平台分类'}}</text>
							</view>
							<u-icon name="arrow-right" ></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="商品分类"  prop="categoryId">
						<view class="u-flex u-row-between" style="width: 100%;" @tap="$mRouter.push({ route: '/pages/sale/classManger/index?type=BrandOwner&isChoose=true&name='+fromData.categoryName+'&id='+fromData.categoryId })">
							<view class="" style="flex:1;">
								<text :style="{'color':fromData.categoryId?'#333':'rgb(192, 196, 204)'}">{{fromData.categoryName||'请选择商品分类'}}</text>
							</view>
							<u-icon name="arrow-right" ></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="商品品牌"  prop="brandId">
						<view class="u-flex u-row-between" style="width: 100%;" @tap="$mRouter.push({ route: '/pages/owners/brandMange/index?isChoose=true&name='+fromData.brandName+'&id='+fromData.brandId })">
							<view class="" style="flex:1;">
								<text :style="{'color':fromData.brandId?'#333':'rgb(192, 196, 204)'}">{{fromData.brandName||'请选择商品分类'}}</text>
							</view>
							<u-icon name="arrow-right" ></u-icon>
						</view>
					</u-form-item>
					
					<u-form-item label="商品介绍"  prop="remarks">
						<u-input v-model="fromData.remarks" :type="'textarea'" placeholder="请输入商品介绍"/>
					</u-form-item>
					<u-form-item label="商品产地" prop="placeOfOrigin">
						<u-input v-model="fromData.placeOfOrigin"placeholder="请输入商品产地"/>
					</u-form-item>
					<u-form-item label="商品原料" prop="rawMaterial">
						<u-input v-model="fromData.rawMaterial"placeholder="请输入商品原料"/>
					</u-form-item>
					
					<u-form-item label="商品详情图" prop="itemDetails">
						<UploadImage :fileList="itemDetailsList" @onSuccess="uploadDetailsChange" @onRemove="uploadDetailsChange" :maxCount="9"></UploadImage>
					</u-form-item>
					
					<u-form-item label="天猫链接">
						<u-input v-model="fromData.tmallUrl"placeholder="请输入天猫链接"/>
					</u-form-item>
					
					<u-form-item label="SEO关键字">
						<u-input v-model="fromData.keyword"placeholder="请输入关键字"/>
					</u-form-item>
					
					<u-form-item label="SEO/分享标题">
						<u-input v-model="fromData.shareTitle"placeholder="请输入SEO/分享标题"/>
					</u-form-item>
					<u-form-item label="SEO/分享简介">
						<u-input v-model="fromData.shareRemarks" :type="'textarea'" placeholder="请输入SEO/分享简介"/>
					</u-form-item>
					<u-form-item label="标签">
						<view class="u-flex u-row-between" style="width: 100%;" @click="chooseTagOpen(fromData.tags)">
							<view class="u-line-1" style="flex:1;" v-if="fromData.tags.length!=0">
								<text style="color: #333;" :key="item.id" v-for="(item,index) in fromData.tags">{{item.name}}{{index!==fromData.tags.length-1?',':''}}</text>
							</view>
							<view v-else>
								<text style="color:rgb(192, 196, 204)">请选择商品标签</text>
							</view>
							<u-icon name="arrow-right" ></u-icon>
						</view>
					</u-form-item>
					<view class="u-flex u-row-between u-m-t-30 u-m-b-30">
						<view class="u-flex">
							<text class="u-m-r-20">是否下架</text>
							<u-switch v-model="fromData.isHaltSale" size="40" active-color="#ffbb1a" inactive-color="#ccc"></u-switch>
						</view>
						<view class="u-flex">
							<text class="u-m-r-20">标记删除</text>
							<u-switch v-model="fromData.isDeleted" size="40" active-color="#ffbb1a" inactive-color="#ccc" ></u-switch>
						</view>
					</view>
				</u-form>
				
				<u-button type="default" :custom-style="customStyle" class="u-m-t-40 u-m-b-40" :hover-class="'none'" @click="saveItemFn">保存</u-button>
				
		</view>
		<u-modal v-model="delModel" ref="delModel" :async-close="true" :content="'您确定要移除此商品吗？'"  @confirm="delItemFn()" ></u-modal>
		<u-popup v-model="chooseTagShow" safe-area-inset-bottom	:closeable="true"  mode="bottom" length="60%">
			<view style="height: 100%;flex-direction: column;" class="u-flex">
				<view class="u-text-center u-p-t-30 u-p-b-30">选择标签</view>
				<view style="flex:1;width: 100%;">
					<choose-tag v-if="chooseTagShow" @getTag="chooseTagEmit" :chooseTagIds="chooseTagList"></choose-tag>
				</view>
				
			</view>
		</u-popup>
	</view>
</template>

<script>
	import UploadImage from '@/components/upload-image/index.vue';
	import ChooseTag from './ChooseTag.vue'
	import { useShopStore } from '@/store/shop.js';
	import { mapState } from 'pinia';
	export default {
		components:{UploadImage,ChooseTag},
		data(){
			return {
				delModel:false,
				chooseTagShow:false,
				chooseTagList:[],
				fromData:{
					categoryId:'',
					platformCategoryId:'',
					brandId:'',
					itemFocus:[],
					itemDetails:[],
					barcode:'',
					tags:[]
				},
				labelStyle:{
					'fontSize':'30rpx',
					'color':'#333',
					'fontWeight':'bold'
				},
				customStyle:{
					color:'#fff',
					background:'#ffbb1a',
					borderRadius:'100rpx',
					height:'88rpx',
					lineHeight:'88rpx',
					fontSize:'34rpx'
				},
				title:'商品',
				itemImageList:[],
				resourceList:[],
				pureResourceList:[],
				videoImageList:[],
				itemDetailsList:[],
				refreshIfNeeded:false,
				rules: {
					name: [{required: true,message: '请输入商品姓名',trigger: ['blur','change']}],
					abbreviation: [{required: true,message: '请输入商品简称',trigger: ['blur','change']}],
					specification: [{required: true,message: '请输入商品规格',trigger: ['blur','change']}],
					// price: [{required: true,message: '请输入商品价格',trigger: ['blur','change']}],
					unit: [{required: true,message: '请输入商品单位',trigger: ['blur','change']}],
					resourceId: [{required: true,message: '请上传商品缩略图',trigger: ['blur','change']}],
					pureResourceId: [{required: true,message: '请上传商品分类图',trigger: ['blur','change']}],
					categoryId: [{required: true,message: '请选择商品分类',trigger: ['blur','change']}],
					brandId: [{required: true,message: '请选择商品品牌',trigger: ['blur','change']}],
					remarks: [{required: true,message: '商品介绍不得为空',trigger: ['blur','change']}],
					placeOfOrigin: [{required: true,message: '商品产地不得为空',trigger: ['blur','change']}],
					rawMaterial: [{required: true,message: '商品原料不得为空',trigger: ['blur','change']}],
				}
				
			}
		},
		onLoad(options) {
			if(options.type === 'edit'){
				// this.from = this.$u.deepClone(options.item);
				this.fromData.id = options.id;
				this.getItemDetailsFn();
				this.title = '编辑商品';
			}else{
				this.title = '新增商品';
			}
		},
		onShow() {
			uni.$off('sendClassData')//建议先销毁一次监听，再进行新的一次监听，否则会出现重复监听的现象
			uni.$off('sendBrandData')//建议先销毁一次监听，再进行新的一次监听，否则会出现重复监听的现象
			uni.$off('sendPlateClass')//建议先销毁一次监听，再进行新的一次监听，否则会出现重复监听的现象
			
			let that = this;
			uni.$once('sendClassData',function(data){
					//这的data就是B页面传递过来的数据
					that.fromData.categoryName=data.name===''?'请选择商品分类':data.name;
					that.fromData.categoryId=data.id===''?null:data.id;
			})
			uni.$once('sendBrandData',function(data){
					//这的data就是B页面传递过来的数据
					that.fromData.brandName=data.name===''?'请选择商品品牌':data.name;
					that.fromData.brandId=data.id===''?null:data.id;
			})
			uni.$once('sendPlateClass',function(data){
					//这的data就是B页面传递过来的数据
					that.fromData.platformCategoryName=data.name===''?'请选择平台分类':data.name;
					that.fromData.platformCategoryId=data.id===''?null:data.id;
			})
		},
		computed:{
			
			...mapState(useShopStore, {
				storeShop: 'shop',
			})	
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods:{
			chooseTagEmit(val){
				this.fromData.tags = val.dataList;
				this.chooseTagList = val.idList;
				this.chooseTagShow = false;
			},
			chooseTagOpen(data){
					this.chooseTagList = data.map(item=>{return item.id});
				this.chooseTagShow = true;
			},
			// 商品图片上传（最多四张）
			uploadItemChange(val){
				this.fromData.itemFocus = val;
			},
			// 商品详情图片上传（最多九张）
			uploadDetailsChange(val){
				this.fromData.itemDetails = val;
			},
			// 商品缩略图上传
			uploadResChange(val){
				this.fromData.resourceId = val;
			},
			// 商品缩略图移除
			uploadResRemove(val){
				this.fromData.resourceId = '';
			},
			// 商品分类图上传
			uploadPureChange(val){
				this.fromData.pureResourceId = val;
			},
			// 商品分类图移除
			uploadPureRemove(val){
				this.fromData.pureResourceId = '';
			},
			// 商品分类图上传
			uploadVideoChange(val){
				this.fromData.videoCoverResourceId = val;
			},
			// 商品分类图移除
			uploadVideoRemove(val){
				this.fromData.videoCoverResourceId = '';
			},
			onVideoSuccess(val){
				if(val.code === 200){
					this.fromData.videoUrl = val.data[0].url;
					this.fromData.videoResourceId = val.data[0].id;
				}else{
					this.$u.toast('上传视频失败')
				}
			},
			onVideoRemove(){
				this.fromData.videoUrl = '';
				this.fromData.videoResourceId = null;
			},
			// 获取商品详情
			async getItemDetailsFn(){
				uni.showLoading({
					title:'loading...'
				});
				let params = {
					shopId:this.storeShop.id,
					id:this.fromData.id
				}
				const res = await this.$newHttp.get('api/BrandOwner/GetItemDetail',{params:params});
				uni.hideLoading();
				if(res.code === 200){
					this.fromData = res.data;
					this.fromData.price = Number(res.data.price);
					this.itemImageList = this.imageListInit('more',res.data.itemFocus);
					this.itemDetailsList = this.imageListInit('more',res.data.itemDetails);
					
					this.resourceList = this.imageListInit('one',res.data.resourceUrl,res.data.resourceId);
					this.pureResourceList = this.imageListInit('one',res.data.pureResourceUrl,res.data.pureResourceId);
					this.videoImageList = this.imageListInit('one',res.data.videoCoverResourceUrl,res.data.videoCoverResourceId);
				}else{
					this.$u.toast('获取商品详情失败')
				}
			},
			// 初始化图片格式
			imageListInit(type,resource,resourceId){
				let ary = [];
				if(type === 'one'){
					if(resource){
						ary.push({
							id:resourceId?resourceId:'',
							url:resource?resource:''
						})
					}
				}else{
					resource.forEach(item=>{
						ary.push({
							id:item.resourceId,
							url:item.url
						})
					})
				};
				return ary;
			},
			// 保存修改或新增
			async saveItemFn(){
				uni.showLoading({
					title:'loading...'
				});
				this.$refs.uForm.validate(async valid => {
					if (valid) {
						if(this.fromData.barcode&&this.fromData.barcode!==''){
							if(this.fromData.barcode.length>13||this.fromData.barcode.length<12){
								uni.hideLoading();
								this.$u.toast('商品编码为12到13位数字组成')
								return false;
							}
						}
						// this.formData.barcode = Number(this.formData.barcode);
						if(this.fromData.price===0||this.fromData.price === ''){
							uni.hideLoading();
							this.$u.toast('终端价格不得为空或为0')
							return false;
						}
						if(this.fromData.itemFocus.length===0){
							uni.hideLoading();
							this.$u.toast('商品图片不得为空')
							return false;
						}
						if(this.fromData.itemDetails.length===0){
							uni.hideLoading();
							this.$u.toast('商品详情图片不得为空')
							return false;
						}
						const res = await this.$newHttp.post('api/v1.2/BrandOwner/SaveItem',this.fromData);
						uni.hideLoading();
						if(res.code === 200){
							uni.showToast({
								title:'保存成功',
								icon:'success'
							});
							this.$mHelper.delayedJump();
						}else{
							this.$u.toast('保存失败')
						}
					} else {
						console.log('验证失败');
					}
				});
				
			},
			// 删除商品
			async delItemFn(){
				uni.showLoading({
					title:'loading...'
				});
				let params = {
					shopId:this.storeShop.id,
					id:this.fromData.id,
					isDeleted:true
				}
				const res = await this.$newHttp.delete('api/BrandOwner/DeleteItem',params);
				uni.hideLoading();
				if(res.code === 200){
					uni.showToast({
						title:'删除成功',
						icon:'success'
					});
					this.$mHelper.delayedJump();
				}else{
					this.$u.toast('删除失败');
					this.$refs.delModel.clearLoading();
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.product-container{
		background-color: #fff;
		min-height: 100%;
	}
</style>